'''
Created on Jun 12, 2012

@author: thomas_dao
'''

from web import base
from web.base import BaseHandler
from web import urls
from web import util
import json
import logging
from google.appengine.ext import ndb
from entity.entity import Option, Poll
from webapp2_extras.appengine.auth.models import User

class CreateHandler(BaseHandler):
    @ndb.synctasklet
    @base.user_required
    def post(self):
        option = Option()
        option.author = util.get_current_user_key()
        option.option = self.request.params.get('option')
        poll_id = self.request.params.get('poll_id')
        option.poll = ndb.Key(Poll, int(poll_id))
        option.put()
        # Return the id back to client
        self.response.write(json.dumps(util.ndb_to_dict(option)))
        

class ReadHandler(BaseHandler):
    def get(self):
        option_id = self.request.params.get('option_id')
        option_key = ndb.Key(Option, int(option_id))
        # Return the id back to client
        self.response.write(json.dumps(util.ndb_to_dict(option_key.get())))
        

class UpdateHandler(BaseHandler):
    def post(self):
        option_id = self.request.params.get('option_id')
        option_key = ndb.Key(Option, int(option_id))
        option = option_key.get()
        
        if option.users is None:
            option.users = []
            
        # Toggle selection
        user_key = util.get_current_user_key()
        if user_key in option.users:
            option.users.remove(user_key)
        else:
            option.users.insert(0, user_key)
        
        option.put()
        # Return the id back to client
        self.response.write(json.dumps(util.ndb_to_dict(option)))
    

class DeleteHandler(BaseHandler):
    def post(self):
        pass    


app = urls.app

def main():
    app.run()

if __name__ == '__main__':
    main()